package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 生成静态文件上传到minIO中
     *
     * @param apArticle
     * @param content
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        //已知文章的id
        //4.1 获取文章内容

        //4.2 文章内容通过freemarker生成html文件
        Template template = null;
        StringWriter out = new StringWriter();
        try {
            template = configuration.getTemplate("article.ftl");
            //数据模型
            Map<String, Object> contentDataModel = new HashMap<>();
            contentDataModel.put("content", JSONArray.parseArray(content));
            //合成
            template.process(contentDataModel, out);

            //4.3 把html文件上传到minio中
            ByteArrayInputStream is = new ByteArrayInputStream(out.toString().getBytes());
            String htmlUrl = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);

            //4.4 修改ap_article表，保存static_url字段
            apArticle.setStaticUrl(htmlUrl);
            apArticleMapper.updateById(apArticle);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}